package com.doit.demo02;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class test02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class c = Class.forName("com.doit.demo.Person");

        //获取空参构造方法 并运行
        Constructor con = c.getConstructor();
        Object obj = con.newInstance(); //Object obj = new Person();
        System.out.println(obj);

        //获取带参构造方法 并运行
        Constructor cons = c.getConstructor(String.class,int.class);
        Object obje = cons.newInstance("柳岩",38); //Object obj = new Person();
        System.out.println(obje);

        method();
        method2();
    }
    public static void method() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class c = Class.forName("com.doit.demo.Person");
        Constructor con = c.getConstructor(String.class, int.class);
        Object obj = con.newInstance("李白", 188);
        System.out.println(obj);
    }
    public static void method2() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class c = Class.forName("com.doit.demo.Person");
        Constructor con = c.getDeclaredConstructor(String.class);

        con.setAccessible(true);
        //暴力反射 不推荐使用,破坏了封装安全

        Object obj = con.newInstance("唐嫣");
        System.out.println(obj);
    }
}
